######################################################################
# File: utils/jinja2.py                            Part of DjangoMUD #
#                                                                    #
# Copyright (C) 2010, Joachim Pileborg.                              #
# All rights reserved.                                               #
#                                                                    #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions #
# are met:                                                           #
#                                                                    #
#   o Redistributions of source code must retain the above copyright #
#     notice, this list of conditions and the following disclaimer.  #
#   o Redistributions in binary form must reproduce the above        #
#     copyright notice, this list of conditions and the following    #
#     disclaimer in the documentation and/or other materials         #
#     provided with the distribution.                                #
#   o Neither the name of the author nor the names of its            #
#     contributors may be used to endorse or promote products        #
#     derived from this software without specific prior written      #
#     permission.                                                    #
#                                                                    #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             #
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        #
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           #
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           #
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS  #
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,#
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,           #
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR #
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY       #
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR     #
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF #
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF    #
# SUCH DAMAGE.                                                       #
######################################################################

# This file handles integration with the Jinja2 template engine.
# See http://jinja.pocoo.org/2/ for more information about Jinja2.

######################################################################

import jinja2

from django.conf import settings

__all__ = [
    "environment",
    "render_to_string",
    "render_to_response",
    ]

######################################################################

global environment

# Setup the template loaders for all possible template directories
template_loaders = []
for td in getattr(settings, 'TEMPLATE_DIRS', ()):
    template_loaders.append(jinja2.FileSystemLoader(td))

for app in settings.INSTALLED_APPS:
    template_loaders.append(jinja2.PackageLoader(app))

# Get the extensions to use
global_exts = getattr(settings, 'JINJA_EXTS', ())

def _autoescape_for_html(template_name):
    if template_name is None or '.' not in template_name:
        return False
    ext = template_name.split('.')[-1]
    return ext in ('html', 'htm', 'xml')

environment = jinja2.Environment(
    loader=jinja2.ChoiceLoader(template_loaders),
    extensions=global_exts,
    autoescape=_autoescape_for_html)

from django.core.urlresolvers import get_callable

global_imports = getattr(settings, 'JINJA_GLOBALS', ())
for imp in global_imports:
    method = get_callable(imp)
    method_name = getattr(method, 'jinja_name', None)
    if method_name is not None:
        environment.globals[method_name] = method
    else:
        environment.globals[method.__name__] = method

global_filters = getattr(settings, 'JINJA_FILTERS', ())
for imp in global_filters:
    method = get_callable(imp)
    method_name = getattr(method, 'jinja_name', None)
    if method_name is not None:
        environment.filters[method_name] = method
    else:
        environment.filters[method.__name__] = method

global_tests = getattr(settings, 'JINJA_TESTS', ())
for imp in global_tests:
    method = get_callable(imp)
    method_name = getattr(method, 'jinja_name', None)
    if method_name is not None:
        environment.tests[method_name] = method
    else:
        environment.tests[method.__name__] = method

default_mimetype = getattr(settings, 'DEFAULT_CONTENT_TYPE')

######################################################################

def render_to_string(filename, context={}):
    template = environment.get_template(filename)
    rendered = template.render(**context)
    return rendered

def render_to_response(filename, context={}, mimetype=default_mimetype, request=None):
    from django.http import HttpResponse

    if request:
        context['request'] = request
    rendered = render_to_string(filename, context)
    return HttpResponse(rendered, mimetype=mimetype)

######################################################################
